﻿using Dapper;
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using Eagles.Base.DataBase;
using Eagles.Base.DataBase.Modle;
using Eagles.Application.Model.Enums;
using Eagles.Application.Model.Common;
using Eagles.DomainService.Model.User;
using Eagles.DomainService.Model.Activity;
using Eagles.Interface.DataAccess.ActivityAccess;

namespace Ealges.DomianService.DataAccess.ActivityData
{
    public class ActivityDataAccess : IActivityAccess
    {
        private readonly IDbManager dbManager;

        public ActivityDataAccess(IDbManager dbManager)
        {
            this.dbManager = dbManager;
        }

        public int CreateActivity(TbActivity reqActivity, int toUserId, out int activityId)
        {
            var result = 0;
            activityId = dbManager.ExecuteScalar<int>(@"insert into eagles.tb_activity (OrgId, BranchId, ActivityName, HtmlContent, BeginTime, EndTime, FromUser, FromUserName, ActivityType, MaxCount, CanComment, 
TestId, MaxUser, Attach1, Attach2, Attach3, Attach4, AttachName1, AttachName2, AttachName3, AttachName4, ImageUrl, IsPublic, OrgReview, BranchReview, ToUserId, ToUserName, Status, CreateType, AuditUserId, CreateTime) 
values (@OrgId, @BranchId, @ActivityName, @HtmlContent, @BeginTime, @EndTime, @FromUser, @FromUserName, @ActivityType, @MaxCount, @CanComment, @TestId, @MaxUser, @Attach1, @Attach2, @Attach3, @Attach4, 
@AttachName1, @AttachName2, @AttachName3, @AttachName4, @ImageUrl, @IsPublic, @OrgReview, @BranchReview, @ToUserId, @ToUserName, @Status, @CreateType, @AuditUserId, @CreateTime); select LAST_INSERT_ID(); ", reqActivity);
            result = dbManager.Excuted(@"insert into eagles.tb_user_activity(OrgId,BranchId,ActivityId,UserId,CreateTime) values (@OrgId,@BranchId,@ActivityId,@UserId,@CreateTime) ",
                new
                {
                    OrgId = reqActivity.OrgId,
                    BranchId = reqActivity.BranchId,
                    ActivityId = activityId,
                    UserId = toUserId, //任务责任人
                    CreateTime = DateTime.Now
                });
            return result;
        }

        public int EditActivity(TbActivity reqActivity, int toUserId)
        {
            var result = 0;
            result = dbManager.Excuted(@"update eagles.tb_activity set OrgId = @OrgId, BranchId = @BranchId, ActivityName = @ActivityName, HtmlContent = @HtmlContent, BeginTime = @BeginTime, EndTime = @EndTime, FromUser = @FromUser, 
FromUserName = @FromUserName, ActivityType = @ActivityType, MaxCount = @MaxCount, CanComment = @CanComment, TestId = @TestId, MaxUser = @MaxUser, Attach1 = @Attach1, Attach2 = @Attach2, Attach3 = @Attach3, Attach4 = @Attach4, 
AttachName1 = @AttachName1, AttachName2 = @AttachName2, AttachName3 = @AttachName3, AttachName4 = @AttachName4, ImageUrl = @ImageUrl, IsPublic = @IsPublic, OrgReview = @OrgReview, BranchReview = @BranchReview, ToUserId = @ToUserId, 
ToUserName = @ToUserName, Status = @Status, CreateType = @CreateType, AuditUserId = @AuditUserId, CreateTime = @CreateTime where ActivityId = @ActivityId; ", reqActivity);
            result = dbManager.Excuted(@"update eagles.tb_user_activity set OrgId = @OrgId, BranchId = @BranchId, UserId = @UserId where ActivityId = @ActivityId ",
                new
                {
                    OrgId = reqActivity.OrgId,
                    BranchId = reqActivity.BranchId,
                    UserId = toUserId, //任务责任人
                    ActivityId = reqActivity.ActivityId
                });
            return result;
        }

        public int EditActivityJoin(TbUserActivity userActivity)
        {
            return dbManager.Excuted(@"insert into eagles.tb_user_activity(OrgId,BranchId,ActivityId,UserId,CreateTime) values (@OrgId,@BranchId,@ActivityId,@UserId,@CreateTime)", userActivity);
        }

        public int EditActivityReview(ActivityTypeEnum type, int activityId, int reviewType)
        {
            var result = 0;
            switch (type)
            {
                case ActivityTypeEnum.Audit:
                    //上级审核任务
                    if (0 == reviewType)
                        result = dbManager.Excuted("update eagles.tb_activity set Status = 0 where ActivityId = @ActivityId and Status = -1 ", new { ActivityId = activityId }); //审核通过
                    else
                        result = dbManager.Excuted("update eagles.tb_activity set Status = -9 where ActivityId = @ActivityId and Status = -1 ", new { ActivityId = activityId }); //审核不通过
                    break;
                case ActivityTypeEnum.Apply:
                    //下级申请完成任务
                    result = dbManager.Excuted("update eagles.tb_activity set Status = 1 where ActivityId = @ActivityId and Status = 0 ", new { ActivityId = activityId }); //2-完成任务待审核
                    break;
            }
            return result;
        }

        public int EditActivityCancel(int activityId)
        {
            return dbManager.Excuted("update eagles.tb_activity set Status = -7 where ActivityId = @ActivityId and (Status = 0 or Status = -1) ", new { ActivityId = activityId }); //活动取消
        }

        public bool EditActivityComplete(int activityId, int isPublic, int completeStatus, int score)
        {
            var status = 0; //不通过,置成初始状态重新审核
            if (completeStatus == 0)
                status = 2; //通过
            var commands = new List<TransactionCommand>()
            {
                new TransactionCommand()
                {
                    CommandString = @"update eagles.tb_activity set Status = @Status, IsPublic = @IsPublic, PublicTime = @PublicTime where ActivityId = @ActivityId and Status = 1",
                    Parameter = new { Status = status, IsPublic = isPublic, PublicTime = DateTime.Now, ActivityId = activityId }
                },
                new TransactionCommand()
                {
                    CommandString = "update eagles.tb_user_activity set RewardsScore = @RewardsScore, CompleteTime=@CompleteTime where ActivityId = @ActivityId",
                    Parameter = new { RewardsScore = score, CompleteTime = DateTime.Now, ActivityId = activityId }
                }
            };
            return dbManager.ExcutedByTransaction(commands);
        }
        
        public int EditActivityFeedBack(TbUserActivity userActivity)
        {
            return dbManager.Excuted(@"update eagles.tb_user_activity set UserFeedBack = @UserFeedBack, FeedBackTime = @FeedBackTime, AttachName1 = @AttachName1, AttachName2 = @AttachName2, AttachName3 = @AttachName3, 
AttachName4 = @AttachName4, Attach1 = @Attach1, Attach2 = @Attach2, Attach3 = @Attach3, Attach4 = @Attach4 where ActivityId = @ActivityId and UserId = @UserId ", userActivity);
        }

        public List<TbUserActivity> GetActivityFeedBack(int activityId, int appId, int userId)
        {
            return dbManager.Query<TbUserActivity>(@"select a.activityId,a.UserId,b.Name,a.UserFeedBack,a.FeedBackTime,a.AttachName1,a.AttachName2,a.AttachName3,a.AttachName4,
a.Attach1,a.Attach2,a.Attach3,a.Attach4 from eagles.tb_user_activity a join eagles.tb_user_info b on a.UserId = b.UserId
where a.ActivityId = @ActivityId and a.OrgId = @OrgId and a.UserId = @UserId ", new { ActivityId = activityId, Orgid = appId, UserId = userId });
        }

        public List<TbActivity> GetActivity(ActivityType activityType, ActivityPage activityPage, TbUserInfo user, int pageIndex = 1, int pageSize = 10)
        {
            var sql = new StringBuilder();
            var dynamicParams = new DynamicParameters();
            dynamicParams.Add("OrgId", user.OrgId);
            dynamicParams.Add("BranchId", user.BranchId);
            dynamicParams.Add("UserId", user.UserId);
            int pageIndexParameter = (pageIndex - 1) * pageSize;
            dynamicParams.Add("PageIndex", pageIndexParameter);
            dynamicParams.Add("PageSize", pageSize);
            switch (activityPage)
            {
                case ActivityPage.All:
                    //所有活动
                    sql.Append(@"select OrgId,BranchId,ActivityId,ActivityName,HtmlContent,BeginTime,EndTime,FromUser,ActivityType,MaxCount,CanComment,TestId,MaxUser,
Attach1,Attach2,Attach3,Attach4,AttachName1,AttachName2,AttachName3,AttachName4,ImageUrl,IsPublic,OrgReview,BranchReview,ToUserId,Status from eagles.tb_activity 
where OrgId = @OrgId and (BranchId = @BranchId or BranchId = 0) and Status not in (-9,-1,-7) or ((FromUser = @UserId or ToUserId = @UserId) and Status in (-9,-1)) 
order by ActivityId desc limit @PageIndex, @PageSize ");
                    break;
                case ActivityPage.Mine:
                    //得到用户参与活动
                    sql.Append(@"select OrgId,BranchId,ActivityId,ActivityName,HtmlContent,BeginTime,EndTime,FromUser,ActivityType,MaxCount,CanComment,TestId,MaxUser,
Attach1,Attach2,Attach3,Attach4,AttachName1,AttachName2,AttachName3,AttachName4,ImageUrl,IsPublic,OrgReview,BranchReview,ToUserId,Status from eagles.tb_activity 
where OrgId = @OrgId and (BranchId = @BranchId or BranchId = 0) and Status  not in (-9,-7) and ActivityId in (select ActivityId from eagles.tb_user_activity where UserId = @UserId) 
order by ActivityId desc limit @PageIndex, @PageSize ");
                    break;
                case ActivityPage.Other:
                    //得到用户未参与活动
                    sql.Append(@"select OrgId,BranchId,ActivityId,ActivityName,HtmlContent,BeginTime,EndTime,FromUser,ActivityType,MaxCount,CanComment,TestId,MaxUser,
Attach1,Attach2,Attach3,Attach4,AttachName1,AttachName2,AttachName3,AttachName4,ImageUrl,IsPublic,OrgReview,BranchReview,ToUserId,Status from eagles.tb_activity 
where OrgId = @OrgId and (BranchId = @BranchId or BranchId = 0) and Status = 0 and ActivityId not in (select ActivityId from eagles.tb_user_activity where UserId = @UserId) 
order by ActivityId desc limit @PageIndex, @PageSize ");
                    break;
                case ActivityPage.Audit:
                    //得到用户待审核
                    sql.Append(@"select OrgId,BranchId,ActivityId,ActivityName,HtmlContent,BeginTime,EndTime,FromUser,ActivityType,MaxCount,CanComment,TestId,MaxUser,
Attach1,Attach2,Attach3,Attach4,AttachName1,AttachName2,AttachName3,AttachName4,ImageUrl,IsPublic,OrgReview,BranchReview,ToUserId,Status from eagles.tb_activity 
where OrgId = @OrgId and (BranchId = @BranchId or BranchId = 0) and Status not in (-9,-7) and AuditUserId = @UserId
order by ActivityId desc limit @PageIndex, @PageSize ");
                    break;
            }
            return dbManager.Query<TbActivity>(sql.ToString(), dynamicParams);
        }
        
        public TbActivity GetActivityDetail(int activityId, int appId)
        {
            var result = dbManager.Query<TbActivity>(@"select OrgId,BranchId,ActivityId,ActivityName,Status,ImageUrl,HtmlContent,BeginTime,EndTime,AttachName1,AttachName2,AttachName3,AttachName4,Attach1,Attach2,Attach3,Attach4,
FromUser,FromUserName,ToUserId,ToUserName,ImageUrl,CreateType,MaxCount,MaxUser,AuditUserId,(select Name from eagles.tb_user_info where AuditUserId = UserId ) as AuditUserName,ifnull(ViewCount,0) as ViewCount from eagles.tb_activity 
where ActivityId = @ActivityId and OrgId = @OrgId ", new { ActivityId = activityId, Orgid = appId });
            if (result != null && result.Any())
                return result.FirstOrDefault();
            return null;
        }

        public List<TbActivity> GetPublicActivity(int appId, bool isHome = false, int branchId = 0, int pageIndex = 1, int pageSize = 10)
        {
            int pageIndexParameter = (pageIndex - 1) * pageSize;
            var sql = new StringBuilder(@"select a.OrgId,a.BranchId,(select BranchName from eagles.tb_branch b where a.BranchId = b.BranchId) BranchName,a.ActivityId,a.ActivityName,a.ImageUrl,a.HtmlContent,a.FromUser,a.FromUserName
a.BeginTime,a.EndTime,a.TestId from eagles.tb_activity a where a.OrgId = @OrgId ");
            //if (isHome)
            //{
            //    sql.Append("and ImageUrl is not null and ImageUrl <> '' ");
            //}
            if (branchId > 0)
            {
                //说明有用户
                sql.AppendFormat("and (IsPublic = 3 and OrgReview = 0 ) or (IsPublic = 2 and BranchId = {0}) and BranchReview = 0 ", branchId);
            }
            else
            {
                sql.Append("and IsPublic = 3 and OrgReview = 0 and BranchReview = 0 ");
            }
            sql.Append("order by ActivityId desc limit @PageIndex, @PageSize");
            return dbManager.Query<TbActivity>(sql.ToString(), new { Orgid = appId, PageIndex = pageIndexParameter, PageSize = pageSize });
        }

        public TbActivity GetPublicActivityDetail(int activityId, int appId)
        {
            var result = dbManager.Query<TbActivity>(@"select OrgId,BranchId,ActivityId,ActivityName,Status,ImageUrl,HtmlContent,BeginTime,EndTime,AttachName1,AttachName2,AttachName3,AttachName4,Attach1,Attach2,Attach3,Attach4,
FromUser,FromUserName,ToUserId,ToUserName,ImageUrl,CreateType,MaxCount,MaxUser,AuditUserId,(select Name from eagles.tb_user_info where AuditUserId = UserId ) as AuditUserName,ifnull(ViewCount,0) as ViewCount from eagles.tb_activity 
where ActivityId = @ActivityId and OrgId = @OrgId and IsPublic = 3 and OrgReview = 0 and BranchReview = 0 ",
                new { ActivityId = activityId, Orgid = appId });
            if (result != null && result.Any())
                return result.FirstOrDefault();
            return null;
        }

        public List<JoinPeople> GetActivityJoinPeople(int activityId)
        {
            var result = dbManager.Query<JoinPeople>(@"select a.UserId, b.Name from eagles.tb_user_activity a 
join eagles.tb_user_info b on a.UserId = b.UserId where ActivityId = @ActivityId ", new {ActivityId = activityId});
            if (result != null && result.Any())
                return result;            
            return null;
        }

        public int GetUserActivityCount(int activityId)
        {
            return dbManager.ExecuteScalar<int>("select count(*) from eagles.tb_user_activity where ActivityId = @ActivityId ", new { ActivityId = activityId });
        }

        public List<TbUserActivity> GetUserActivity(int activityId, int userId)
        {
            var sql = new StringBuilder();
            var parameter = new StringBuilder();
            var dynamicParams = new DynamicParameters();
            parameter.Append("and UserId = @UserId ");
            dynamicParams.Add("UserId", userId);
            parameter.Append("and ActivityId = @ActivityId ");
            dynamicParams.Add("ActivityId", activityId);
            sql.AppendFormat(@"select OrgId,BranchId,ActivityId,UserId,UserFeedBack,CreateTime,Status,CompleteTime,RewardsScore,Attach1,Attach2,Attach3,Attach4,
AttachName1,AttachName2,AttachName3,AttachName4 from eagles.tb_user_activity where 1=1 {0}  ", parameter);
            return dbManager.Query<TbUserActivity>(sql.ToString(), dynamicParams);
        }
    }
}